<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>文字滚动效果</title>
  </head>
  <style>
    .container {
      display: flex;
      align-items: center;
    }
    .title {
      float: left;
      font-size: 16px;
      font-weight: normal;
      margin: 0;
      margin-left: 20px;
    }
    .list {
      float: left;
      list-style: none;
      padding: 0;
      height: 30px;
      overflow: hidden scroll;
      margin: 0;
      margin-left: 50px;
    }
    .list li {
      height: 30px;
      line-height: 30px;
    }
  </style>
  <body>
    <div class="container">
      <h1 class="title">最新公告</h1>
      <ul class="list">
        <li>1你好</li>
        <li>2世界</li>
        <li>3!</li>
      </ul>
    </div>
  </body>
  <script>
    // 初始化
    (function () {
      var list = document.querySelector(".list");
      // 1. 将列表中的第一个元素克隆到列表的最后一个
      function cloneFirstItem() {
        var firstItem = list.children[0];
        var firstItemClone = firstItem.cloneNode(true); // true / false 标识是否启用深度克隆
        list.appendChild(firstItemClone);
      }
      cloneFirstItem();
      // 2. 滚动，每隔一段时间，将列表滚动到下一个为止
      // 滚动的间隔时间
      const duration = 1000;
      const itemHeight = 30;
      var currIndex = 0;
      setInterval(moveNext, duration);
      // 将列表滚动至下一个位置
      function moveNext() {
        var from = currIndex * itemHeight;
        currIndex++;
        var to = currIndex * itemHeight;
        var totalDuration = 500; // 变化动画的总时间
        var duration = 10; // 动画的变化间隔时间
        var times = totalDuration / duration; // 变化的次数
        var dis = (to - from) / times; // 每次变化的量
        var timerId = setInterval(function () {
          from += dis;
          if (from >= to) {
            // 到达目标值了
            clearInterval(timerId);
            // 如果是最后一项，
            if (currIndex === list.children.length - 1) {
              console.log("滚动到了最后一项");
              currIndex = 0;
              from = 0;
            }
          }
          list.scrollTop = from;
        }, duration);
      }

      // 慢慢滚动
    })();
  </script>
</html>
